<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport"
          content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>
<body>
<script>
    //起床 -> 刷牙 -> 吃饭 -> 出门  要是突然想在刷牙之前上厕所，改起来就很简单

    /*new Promise((resolve,reject) => {
        setTimeout(() => {
            console.log("起床")
            resolve()
        },1000)
    })
        .then(() => {
            return new Promise((resolve,reject) => {
                setTimeout(() => {
                    console.log("上厕所")
                    resolve()
                },1000)
            })
        })
        .then(() => {
            return new Promise((resolve,reject) => {
                setTimeout(() => {
                    console.log("刷牙")
                    resolve()
                },1000)
            })
        })
        .then(() => {
            return new Promise((resolve,reject) => {
                setTimeout(() => {
                    console.log("吃饭")
                    resolve()
                },1000)
            })
        })
        .then(() => {
            return new Promise((resolve,reject) => {
                setTimeout(() => {
                    console.log("出门")
                    resolve()
                },1000)
            })
        })*/

    //function (){} 等价于 () => {}
    //上面的函数看起来还是有点麻烦，我们对其进行封装
    function job(work,time){
        return (s) => new Promise((resolve,reject) => {
            setTimeout(() => {
                let score = Math.floor(Math.random()*20) + s
                console.log(work,score)
                if(Math.random() < 0.01){ //有0.01的概率会触发reject，reject可以传参数，在哪一步失败的
                    reject(work)
                }else{
                    resolve(score) //接收一个参数得分，触发resolve，则下一次执行就能拿到这个得分
                }
            },time)
        })
    }

    job("起床",1000)(0) //一开始这里的得分传入的是0，给上面那个形参s接收
        .then(job("刷牙",1000))
        .then(job("吃饭",1000))
        .then(job("出门",1000))
        .catch((err)=>{ //catch接收的参数，用形参err表示，实参是来自reject的（work）
            console.log("catch error",err)
        })
        .finaly(()=>{
            console.log("不管成功与否，最后都会执行finaly")
        })



</script>
</body>
</html>